//
//  YLCPostInfoMainView.m
//  YouLe
//
//  Created by 初程程 on 2018/1/9.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCPostInfoMainView.h"
#import "YLCDiscussCell.h"
#import "YLCDiscussModel.h"
#import "YLCPostInfoHeadView.h"
#import "YLCReplyView.h"
#import "YLCVideoInfoHeadView.h"
#import "YLCGoodsInfoHeadView.h"
#import "YLCSendTextView.h"
#import "THPlayerController.h"
#import "YLCChatBaseViewController.h"
#import "YLCDynamicHeadView.h"
#import "YLCReplyNumberCell.h"
#define POST_CELL @"YLCDiscussCell"
#define POST_HEAD @"YLCPostInfoHeadView"
#define VIDEO_HEAD @"YLCVideoInfoHeadView"
#define GOOD_INFO  @"YLCGoodsInfoHeadView"
#define DYNAMIC_HEAD @"YLCDynamicHeadView"
#define NUMBER_CELL @"YLCReplyNumberCell"
@interface YLCPostInfoMainView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>
@end
@implementation YLCPostInfoMainView
{
    UICollectionView *postTable;
    YLCReplyView *replyView;
    YLCSendTextView *sendTextView;
    BOOL isRelyOwner;
    NSInteger selectIndex;
    YLCVideoInfoHeadView *videoHeadView;
}
- (void)videoStop{
    [videoHeadView videoStop];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];

        [self createCustomViews];
    }
    return self;
}
- (void)setDataList:(NSArray *)dataList{
    
    _dataList = dataList;
    
    [postTable reloadData];
}
- (void)setModel:(YLCQuestionModel *)model{
    _model = model;
    if (_infoState==TieziState) {
        [model downLoadHTMLAttrWithComplete:^{
            _model = model;
            [postTable reloadData];
        }];
    }
    [self setCollectionBtnWithIsCollect:model.is_collect];
    [postTable reloadData];
}
- (void)setVideoModel:(YLCVideoLiftInfoModel *)videoModel{
    _videoModel = videoModel;
    replyView.likeBtn.selected = [videoModel.is_top isEqualToString:@"1"];
    [self setCollectionBtnWithIsCollect:videoModel.is_collect];
    [postTable reloadData];
}
- (void)setInfoState:(YLCDynamicInfoState)infoState{
    
    _infoState = infoState;
    
    replyView.isVideo = _infoState== VideoLifeState;
    
    if (infoState==TieziState) {
        replyView.talkBtn.hidden = YES;
    }
    replyView.type = _infoState;
    [postTable reloadData];
}
- (void)setGoodModel:(YLCGoodsModel *)goodModel{
    _goodModel = goodModel;
    [self setCollectionBtnWithIsCollect:goodModel.is_collect];
    [postTable reloadData];
}
- (void)setComment_num:(NSString *)comment_num{
    _comment_num = comment_num;
    
    [postTable reloadData];
}
- (void)setCollectionBtnWithIsCollect:(NSString *)collect{
    
    replyView.collectBtn.selected = [collect isEqualToString:@"1"];
    
}
- (void)createCustomViews{
    self.reloadSignal = [RACSubject subject];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    flow.minimumLineSpacing = 1;
    
    postTable = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
    
    postTable.backgroundColor = YLC_COMMON_BACKCOLOR;
    
    [postTable registerClass:[YLCDiscussCell class] forCellWithReuseIdentifier:POST_CELL];
    
    [postTable registerClass:[YLCPostInfoHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:POST_HEAD];
    
    [postTable registerClass:[YLCVideoInfoHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:VIDEO_HEAD];
    
    [postTable registerClass:[YLCGoodsInfoHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:GOOD_INFO];
    
    [postTable registerClass:[YLCDynamicHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:DYNAMIC_HEAD];
    
    [postTable registerClass:[YLCReplyNumberCell class] forCellWithReuseIdentifier:NUMBER_CELL];
    
    postTable.delegate = self;
    
    postTable.dataSource = self;
    
    [self addSubview:postTable];
    
    CGFloat height = kDevice_Is_iPhoneX?104:70;
    
    replyView = [[YLCReplyView alloc] initWithFrame:CGRectMake(0, 0, self.frameWidth, height)];
    
    replyView.inputTextView.delegate = self;
    
    [replyView.collectBtn addTarget:self action:@selector(gotoCollect:) forControlEvents:UIControlEventTouchUpInside];
    
    [replyView.talkBtn addTarget:self action:@selector(gotoTalke) forControlEvents:UIControlEventTouchUpInside];
    
    [replyView.likeBtn addTarget:self action:@selector(getLike:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:replyView];
    
    sendTextView = [[YLCSendTextView alloc] initWithFrame:CGRectMake(0, kScreenHeight-150, self.frameWidth, 150)];
    
    [sendTextView.sendBtn addTarget:self action:@selector(sendTextViewText) forControlEvents:UIControlEventTouchUpInside];
}
- (void)getLike:(UIButton *)sender{
    NSString *tip = @"";
    if (sender.selected) {
        tip = @"点赞取消";
    }else{
        tip = @"点赞成功";
    }
    NSString *path = @"";
    
    if (_videoModel.isTrain) {
        path = @"app/train/videoTop";
    }else{
        path = @"app/videoLife/top";
    }
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    [YLCNetWorking loadNetServiceWithParam:@{@"token":userModel.token,@"userId":userModel.user_id,@"videoId":_videoModel.id} method:@"POST" urlPath:path delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            
            return ;
        }
        [SVProgressHUD showSuccessWithStatus:tip];
        sender.selected = !sender.selected;
        [self.reloadSignal sendNext:@""];
    }];
}
- (void)gotoTalke{
    if (![YLCLoginManager checkLoginStateWithTarget:self]) {
        return;
    }
    NSString *userName = @"";
    NSString *userId = @"";
    switch (_infoState) {
        case QuestionMineState:
            userId = _model.user_id;
            userName = _model.user_name;
            break;
        case QuestionMineEditState:
            userId = _model.user_id;
            userName = _model.user_name;
            break;
        case QuestionNormalState:
            userId = _model.user_id;
            userName = _model.user_name;
            break;
        case VideoLifeState:
            userId = _videoModel.user_id;
            userName = _videoModel.nick_name;
            break;
        case GoodNormalState:
            userId = _goodModel.user_id;
            userName = _goodModel.nick_name;
            break;
        default:
            break;
    }
    YLCChatBaseViewController *con = [[YLCChatBaseViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:userId];
    
    con.title = userName;
    
    [(UINavigationController *)[YLCFactory currentNav] pushViewController:con animated:YES];
}
- (void)gotoCollect:(UIButton *)sender{
    
    NSString *path = @"";
    NSString *tip = @"";
    if (sender.selected) {
        path = @"app/collect/cancel";
        tip = @"取消成功";
    }else{
        path = @"app/collect/doSave";
        tip = @"收藏成功";
    }
    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    NSString *type = @"";
    NSString *caseId = @"";
    switch (_infoState) {
        case QuestionNormalState:
            caseId = _model.id;
            type = @"4";
            break;
        case QuestionMineState:
            type = @"4";
            break;
        case QuestionMineEditState:
            type = @"4";
            break;
        case VideoLifeState:
            type = @"";
            break;
        case GoodNormalState:
            type = @"2";
            caseId = _goodModel.goodsId;
            break;
        case TieziState:
            type = @"5";
            caseId = _model.id;
            break;
        default:
            break;
    }
    if (JK_IS_STR_NIL(caseId)) {
        caseId = @"";
    }
    [YLCNetWorking loadNetServiceWithParam:@{@"token":model.token,@"userId":model.user_id,@"type":type,@"relationId":caseId} method:@"POST" urlPath:path delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            
            return ;
        }
        [SVProgressHUD showSuccessWithStatus:tip];
    }];
    if (replyView.collectBtn.selected) {
        replyView.collectBtn.selected = NO;
    }else{
        replyView.collectBtn.selected = YES;
    }
}
- (void)sendTextViewText{
    if (![YLCLoginManager checkLoginStateWithTarget:self]) {
        return;
    }
    if (isRelyOwner) {
        [self sendContent];
    }else{
        [self sendReply];
    }
}
- (void)sendReply{
    NSString *path = @"";
    NSDictionary *param = @{};
    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    YLCDiscussModel *discussModel = _dataList[selectIndex-1];
    if (JK_IS_STR_NIL(sendTextView.textView.text)) {
        [SVProgressHUD showErrorWithStatus:@"请输入回复信息"];
        return;
    }
    if (_infoState==QuestionNormalState) {
        path = @"app/case/reply";
        if (JK_IS_STR_NIL(_model.id)) {
            [SVProgressHUD showErrorWithStatus:@"问答信息异常"];
            return;
        }
        if (JK_IS_STR_NIL(discussModel.id)) {
            [SVProgressHUD showErrorWithStatus:@"评论异常"];
        }
        param = @{@"token":model.token,@"userId":model.user_id,@"caseId":_model.id,@"content":sendTextView.textView.text,@"commentId":discussModel.id};
    }
    if (_infoState==GoodNormalState) {
        path = @"app/goods/reply";
        if (JK_IS_STR_NIL(_goodModel.goodsId)) {
            [SVProgressHUD showErrorWithStatus:@"问答信息异常"];
            return;
        }

        param = @{@"token":model.token,@"userId":model.user_id,@"goodsId":_goodModel.goodsId,@"content":sendTextView.textView.text,@"commentId":discussModel.id};
    }
    if (_infoState==TieziState) {
        path = @"app/forum/reply";
        if (JK_IS_STR_NIL(_model.id)) {
            [SVProgressHUD showErrorWithStatus:@"问答信息异常"];
            return;
        }
        if (JK_IS_STR_NIL(sendTextView.textView.text)) {
            [SVProgressHUD showErrorWithStatus:@"请输入回复信息"];
            return;
        }
        param = @{@"token":model.token,@"userId":model.user_id,@"forumId":_model.id,@"content":sendTextView.textView.text,@"commentId":discussModel.id};
    }
    if (_infoState==VideoLifeState) {
        if (_videoModel.isTrain) {
            path = @"app/train/videoReply";
            if (JK_IS_STR_NIL(_videoModel.id)) {
                [SVProgressHUD showErrorWithStatus:@"视频信息异常"];
                return;
            }
            
            param = @{@"token":model.token,@"userId":model.user_id,@"videoId":_videoModel.id,@"content":sendTextView.textView.text,@"commentId":discussModel.id};

        }else{
            path = @"app/videoLife/reply";
            if (JK_IS_STR_NIL(_videoModel.id)) {
                [SVProgressHUD showErrorWithStatus:@"视频信息异常"];
                return;
            }
            param = @{@"token":model.token,@"userId":model.user_id,@"videoId":_videoModel.id,@"content":sendTextView.textView.text,@"commentId":discussModel.id};
        }
    }

    
    [YLCNetWorking loadNetServiceWithParam:param method:@"POST" urlPath:path delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        [SVProgressHUD showSuccessWithStatus:@"回复成功"];
        [self.reloadSignal sendNext:@""];
        [sendTextView removeFromSuperview];
        sendTextView.frame = CGRectMake(0, kScreenHeight-150, self.frameWidth, 150);
        sendTextView.textView.text = @"";
    }];
}
- (void)sendContent{
    NSString *path = @"";
    NSDictionary *param = @{};
    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    if (JK_IS_STR_NIL(sendTextView.textView.text)) {
        [SVProgressHUD showErrorWithStatus:@"请输入回复信息"];
        return;
    }
    if (_infoState==QuestionNormalState) {
        path = @"app/case/comment";
        if (JK_IS_STR_NIL(_model.id)) {
            [SVProgressHUD showErrorWithStatus:@"问答信息异常"];
            return;
        }
        param = @{@"token":model.token,@"userId":model.user_id,@"caseId":_model.id,@"content":sendTextView.textView.text};
    }
    if (_infoState==GoodNormalState) {
        path = @"app/goods/comment";
        if (JK_IS_STR_NIL(_goodModel.goodsId)) {
            [SVProgressHUD showErrorWithStatus:@"物品信息异常"];
            return;
        }
        param = @{@"token":model.token,@"userId":model.user_id,@"goodsId":_goodModel.goodsId,@"content":sendTextView.textView.text};
    }
    if (_infoState==TieziState) {
        path = @"app/forum/comment";
        if (JK_IS_STR_NIL(_model.id)) {
            [SVProgressHUD showErrorWithStatus:@"问答信息异常"];
            return;
        }
        param = @{@"token":model.token,@"userId":model.user_id,@"forumId":_model.id,@"content":sendTextView.textView.text};
    }
    if (_infoState==VideoLifeState) {
        if (JK_IS_STR_NIL(_videoModel.id)) {
            [SVProgressHUD showErrorWithStatus:@"视频信息异常"];
            return;
        }
        if (_videoModel.isTrain) {
            path = @"app/train/videoComment";

            param = @{@"token":model.token,@"userId":model.user_id,@"videoId":_videoModel.id,@"content":sendTextView.textView.text};
        }else{
            path = @"app/videoLife/comment";
            param = @{@"token":model.token,@"userId":model.user_id,@"videoId":_videoModel.id,@"content":sendTextView.textView.text};
        }

    }

    
    [YLCNetWorking loadNetServiceWithParam:param method:@"POST" urlPath:path delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        [SVProgressHUD showSuccessWithStatus:@"回复成功"];
        [self.reloadSignal sendNext:@""];
        [sendTextView removeFromSuperview];
        sendTextView.frame = CGRectMake(0, kScreenHeight-150, self.frameWidth, 150);
    }];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    isRelyOwner = YES;
    [self showAnimation];
    return NO;
}
- (void)showAnimation{
    
    [self addSubview:sendTextView];
    
    [sendTextView.textView becomeFirstResponder];
}
- (void)keyboardWillHide:(NSNotification *)notification{
    sendTextView.textView.text = @"";
//    NSDictionary *userInfo = notification.userInfo;
//    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [sendTextView removeFromSuperview];
    
    sendTextView.frame = CGRectMake(0, kScreenHeight-150, self.frameWidth, 150);
}
- (void)keyboardDidHide:(NSNotification *)notification{
    
}
- (void)keyboardDidShow:(NSNotification *)notification{
    
}
- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    [UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        sendTextView.frame = CGRectMake(0, keyboardF.origin.y-240, kScreenWidth, 150);
    } completion:^(BOOL finished) {
        
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _dataList.count+1;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        YLCReplyNumberCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NUMBER_CELL forIndexPath:indexPath];

        cell.number = _comment_num;

        return cell;
    }
    YLCDiscussCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:POST_CELL forIndexPath:indexPath];
    
    if (indexPath.row-1<_dataList.count) {
        
        cell.model = _dataList[indexPath.row-1];
        
    }
    if (_infoState==QuestionNormalState) {
        [cell configAcceptWithModel:_model];
    }
    cell.type = _infoState;
    
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind==UICollectionElementKindSectionHeader) {
        
        if (_infoState==QuestionNormalState) {
            
            YLCPostInfoHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:POST_HEAD forIndexPath:indexPath];
            
            headView.model = _model;
            
            return headView;
            
        }
        
        if (_infoState==GoodNormalState) {
            
            YLCGoodsInfoHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:GOOD_INFO forIndexPath:indexPath];
            
            headView.model = _goodModel;
            
            return headView;
        }
        
        if (_infoState==TieziState) {
            
            YLCDynamicHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:DYNAMIC_HEAD forIndexPath:indexPath];
            
            headView.model = _model;
            
            return headView;
            
        }
        videoHeadView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:VIDEO_HEAD forIndexPath:indexPath];
        
        videoHeadView.infoModel = _videoModel;
            
        return videoHeadView;
        
    }
    return nil;

}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return CGSizeMake(self.frameWidth, 40);
    }
    YLCDiscussModel *model = _dataList[indexPath.row-1];

    return CGSizeMake(self.frameWidth, [model getCellHeightWithWidth:self.frameWidth]);
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (_infoState==QuestionNormalState) {
        
        CGFloat width = self.frameWidth;
        
        CGFloat height = 60+20+30+10+10+10+5+30+20;
        
        CGSize size = [YLCFactory getStringSizeWithString:_model.content width:width-20 font:14];
        
        height+=size.height;
        
        height+=_model.imglist.count*205;
        
        return CGSizeMake(width, height+80);
    }
    if (_infoState==GoodNormalState) {
        
        CGFloat width = self.frameWidth;
        
        CGFloat height = 90;
        
        CGSize size = [YLCFactory getStringSizeWithString:_goodModel.goodsDescription width:width-20 font:14];
        
        height+=size.height;
        
        height+=_goodModel.img_src.count*205+50;
        
        return CGSizeMake(width, height);
        
    }
    if (_infoState==TieziState) {

        if (_model.hasLoad) {
            CGRect rect = [_model.htmlAttr boundingRectWithSize:CGSizeMake(self.frameWidth-36, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
            
            return CGSizeMake(self.frameWidth, 260+rect.size.height);
        }
        return CGSizeMake(self.frameWidth, 260);
    }
    return CGSizeMake(self.frameWidth, 400);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    selectIndex = indexPath.row;
    isRelyOwner = NO;
    [self showAnimation];
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 0, 10, 0);
}
- (void)layoutSubviews{
    [super layoutSubviews];
    
    [postTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsMake(0, 0, kDevice_Is_iPhoneX?104:70, 0));
    }];
    
    CGFloat height = kDevice_Is_iPhoneX?104:70;
    
    WS(weakSelf)
    
    [replyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(postTable.mas_left);
        make.top.equalTo(postTable.mas_bottom);
        make.width.equalTo(weakSelf.frameWidth);
        make.height.equalTo(height);
    }];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
